import wsgiref.handlers
from google.appengine.ext import webapp
import common
import logging

SETTING_ADDRESS = 'setting_address'
SETTING_TITLE = 'setting_title'
SETTING_TELEPHONE = 'setting_telephone'

class HomeHandler(common.TemplateRequestHandler):
    def get(self):
        self.generate('admin.home.html',)
        inited = common.setting.get('admin_init')
        if inited is None or inited!= 'true':
            self.init_firsttime()
    
    def init_firsttime(self):
        common.columns.init()
        common.setting.set('admin_init', 'true')

class InitHandler(common.TemplateRequestHandler):
    def get(self):
        common.columns.init()
        self.generate('admin.home.html', {'success': True})
        
class SpecialistHandler(common.TemplateRequestHandler):
    def get(self):
        items = common.columns.get_specialist_items(20)
        specialtitle = common.columns.get_title_by_cid(common.COLUMN_TITLE_SPECIALIST)
        self.generate('admin.specialist.html',{'items': items, 
                                             'specialtitle': specialtitle,
                                             })

class SpecialHandler(common.TemplateRequestHandler):
    def get(self):
        key = self.request.get('key', None)
        action = self.request.get('action', None)
        item = None
        if key is None:
            if action is None:
                action = "new"
        else:
            item = common.columns.get(key)
        if action == 'delete':
            item.delete()
            self.redirect('/admin/specialist')
        else:
            specialtitle = common.columns.get_title_by_cid(common.COLUMN_TITLE_SPECIALIST)
            self.generate('admin.special.html',{'item': item,  
                                                'specialtitle': specialtitle,
                                                'action': action,
                                                 })
    
    def post(self):
        key = self.request.get('key', None)
        action = self.request.get('action', None)
        title = self.request.get('text_title')
        success = False
        item = None
        content = self.request.get('editorHtml')
        if action == "new":
            item = common.columns.add_specialist_item(title, content)
        elif action == 'edit' and key:
            item = common.columns.edit_specialist_item(key, title, content)
        if item is None:
            success = False
        else:
            success = True
        specialtitle = common.columns.get_title_by_cid(common.COLUMN_TITLE_SPECIALIST)
        self.generate('admin.special.html',{'item': item, 
                                             'success': success,
                                             'action':action,
                                             'specialtitle': specialtitle,
                                             })
class KBHandler(common.TemplateRequestHandler):
    def get(self):
        key = self.request.get('key', None)
        action = self.request.get('action', None)
        item = None
        if key is None:
            if action is None:
                action = "new"
        else:
            item = common.columns.get(key)
        if action == 'delete':
            item.delete()
            self.redirect('/admin/knowledgebase')
        else:
            specialtitle = common.columns.get_title_by_cid(common.COLUMN_TITLE_KB)
            self.generate('admin.kb.html',{'item': item,  
                                   'specialtitle': specialtitle,
                                         'action': action,
                                                 })
    
    def post(self):
        key = self.request.get('key', None)
        action = self.request.get('action', None)
        title = self.request.get('text_title')
        success = False
        item = None
        content = self.request.get('editorHtml')
        if action == "new":
            item = common.columns.add_kb_item(title, content)
        elif action == 'edit' and key:
            item = common.columns.edit_kb_item(key, title, content)
        if item is None:
            success = False
        else:
            success = True
        specialtitle = common.columns.get_title_by_cid(common.COLUMN_TITLE_KB)
        self.generate('admin.kb.html',{'item': item, 
                                    'success': success,
                                     'action': action,
                               'specialtitle': specialtitle,
                                             })
class MembersHandler(common.TemplateRequestHandler):
    def get(self):
        items = common.members.get_members()
        membertitle = common.columns.get_title_by_cid(common.COLUMN_TITLE_MEMBER)
        self.generate('admin.members.html',{'items': items, 
                                            'membertitle': membertitle,
                                             })
        
class MemberHandler(common.TemplateRequestHandler):
    def get(self):
        key = self.request.get('key', None)
        action = self.request.get('action', None)
        item = None
        if key is None:
            if action is None:
                action = "new"
        else:
            item = common.members.get(key)
        if action == 'delete':
            item.delete()
            self.redirect('/admin/members')
        else:
            membertitle = common.columns.get_title_by_cid(common.COLUMN_TITLE_MEMBER)
            self.generate('admin.member.html',{'item': item,  
                                                'membertitle': membertitle,
                                                'action': action,
                                                 })
    
    def post(self):
        key = self.request.get('key', None)
        action = self.request.get('action', None)
        name = self.request.get('text_name')
        title = self.request.get('text_title')
        subject = self.request.get('text_subject')
        portrait = self.request.get('text_portrait')
        success = False
        item = None
        profile = self.request.get('editorHtml')
        if action == "new":
            item = common.members.add_member(name, title, subject, profile, portrait)
        elif action == 'edit' and key:
            item = common.members.edit_member(key, name, title, subject, profile, portrait)
        if item is None:
            success = False
        else:
            success = True
        membertitle = common.columns.get_title_by_cid(common.COLUMN_TITLE_MEMBER)
        self.generate('admin.member.html',{'item': item, 
                                           'success': success,
                                           'action':action,
                                           'membertitle': membertitle,
                                             })

class ContentHandler(common.TemplateRequestHandler):
    def get(self):
        colkey = self.request.get('column', None)
        items = None
        item = None
        if colkey is None:
            items = common.columns.get_top_navitems()
        else:
            item = common.columns.get(colkey)
        self.generate('admin.content.html',{'column_title':'Setting', 
                                             'columns': items, 
                                             'column': item, 
                                             })
    def post(self):
        colkey = self.request.get('columnkey', None)
        if colkey is None:
            self.error(403)
            return
        column = common.columns.get(colkey)
        if column is None:
            logging.error('input column key is invalid')
            self.error(403)
            return
        content = self.request.get('editorHtml')
        column.content = content
        column.put()
        self.generate('admin.content.html',{'column_title':'Setting', 
                                             'columns': None, 
                                             'success': True, 
                                             'column': column, 
                                             })
class KnowledgebaseHandler(common.TemplateRequestHandler):
    def get(self):
        items = common.columns.get_kb_items(20)
        specialtitle = common.columns.get_title_by_cid(common.COLUMN_TITLE_KB)
        self.generate('admin.kblist.html',{'items': items, 
                                    'specialtitle': specialtitle,
                                             })

class SettingHandler(common.TemplateRequestHandler):
    def get(self):
        items = common.columns.get_top_navitems()
        address = {'title':SETTING_ADDRESS, 'value':common.setting.get(SETTING_ADDRESS)}
        sitename = {'title':SETTING_TITLE, 'value':common.setting.get(SETTING_TITLE)}
        telephone = {'title':SETTING_TELEPHONE, 'value':common.setting.get(SETTING_TELEPHONE)}
        logging.info('items count: %d'%len(items))
        self.generate('admin.setting.html', {'column_title':'Setting', 
                                             'columns': items, 
                                             'address':address, 
                                             'sitename': sitename, 
                                             'telephone': telephone, 
                                             })
    def post(self):
        result = True
        address = {'title':SETTING_ADDRESS, 'value':None}
        sitename = {'title':SETTING_TITLE, 'value':None}
        telephone = {'title':SETTING_TELEPHONE, 'value':None}
        try:
            for k,v in self.request.params.items():
                if k.find('column_') > -1:
                    splits = k.split('_')
                    colkey = splits[1]
                    column = common.columns.get(colkey)
                    if column:
                        logging.info('original column title: %s'%column.title)
                        logging.info('new title:%s'%v)
                        if column.title != v:
                            column.title = v
                            column.put()
                elif k == SETTING_ADDRESS:
                    common.setting.set(SETTING_ADDRESS, v)
                    address['value'] = v
                elif k == SETTING_TITLE:
                    common.setting.set(SETTING_TITLE, v)
                    sitename['value'] = v
                elif k == SETTING_TELEPHONE:
                    common.setting.set(SETTING_TELEPHONE, v)
                    telephone['value'] = v
        except Exception, e:
            logging.error(e)
            result = False
        items = common.columns.all().fetch(20, 0)       
        self.generate('admin.setting.html', {'column_title':'Setting', 
                                             'columns': items, 
                                             'success': result, 
                                             'columns': items, 
                                             'address':address, 
                                             'sitename': sitename,
                                             'telephone': telephone,  
                                             })
        
def main():
    application = webapp.WSGIApplication([
            ('/admin/setting.*', SettingHandler),
            ('/admin/content.*', ContentHandler),
            ('/admin/init.*', InitHandler),
            ('/admin/specialist.*', SpecialistHandler),
            ('/admin/knowledgebase.*', KnowledgebaseHandler),
            ('/admin/special.*', SpecialHandler),
            ('/admin/kb.*', KBHandler),
            ('/admin/members.*', MembersHandler),
            ('/admin/member.*', MemberHandler),
            ('/admin.*', HomeHandler)
            ],debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
    main()        